/**

 * @author admin

 * 2014骞?鏈?鏃?

 */

package com.tmall.testgen.client.runinspring.push.jmx;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.tmall.testgen.client.runinspring.push.TestGenMain;

public class Compute  implements ComputeMBean{
	private  XStream xstream = new XStream(new DomDriver  ());
	
	
	public ComputeResult compute(String clazz, String methodName,Class[] paramTypes, String[] paramStrs){
		
		try {
			Object[] params=null;
			if(paramStrs!=null&&paramStrs.length>0){
				params=new Object[paramStrs.length];
				for(int i=0;i<paramStrs.length;i++){
					params[i]=xstream.fromXML(paramStrs[i]);
				}
			}
		
			
			return SpringController.getComputeResult(clazz, methodName, paramTypes,params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
			
	}

	@Override
	public void stopService() {
		synchronized (TestGenMain.synObject) {
		    System.out.println("compute释放锁定。。。");
			TestGenMain.synObject.notifyAll();
		}
	}

	private void startHsf(String hsfPath) throws Exception, IllegalAccessException, InvocationTargetException{
		hsfPath=normalizePath(hsfPath);
		hsfPath=hsfPath.replaceAll("/taobao-hsf.sar", "");
		int pos=hsfPath.lastIndexOf("/");
		String hsfRoot=hsfPath.substring(0, pos);
		String version=hsfPath.substring(pos+1);
		
		
		Class startClazz=Class.forName("com.taobao.hsf.hsfunit.HSFEasyStarter");
		Method m=startClazz.getMethod("start", String.class,String.class);
		m.invoke(startClazz,  hsfRoot, version);
	}

	@Override
	public InitApplicationContextResult initApplicationContext(String configPath,Boolean isUseHsf,String hsfPath) {
		
		InitApplicationContextResult result=new InitApplicationContextResult();
		try {
			if(isUseHsf){
				startHsf(hsfPath);
			}
			SpringController.initApplicationContext( configPath);
			result.setDbInfoes(SpringController.getDbInfo());
			result.setSucc(true);
			result.setPid(getPid());
			
			
		} catch (Exception e) {
			result.setSucc(false);
			e.printStackTrace();
			synchronized (TestGenMain.synObject) {
				TestGenMain.synObject.notifyAll();
			}
		}
		return result;
	}
	
	
	private static final String normalizePath(String path)
    {
        // Normalize the slashes and add leading slash if necessary
        String normalized = path;
        if (normalized.indexOf('\\') >= 0)
        {
            normalized = normalized.replace('\\', '/');
        }

        if (!normalized.startsWith("/"))
        {
            normalized = "/" + normalized;
        }

        // Resolve occurrences of "//" in the normalized path
        while (true)
        {
            int index = normalized.indexOf("//");
            if (index < 0)
                break;
            normalized = normalized.substring(0, index) +
            normalized.substring(index + 1);
        }

        // Resolve occurrences of "%20" in the normalized path
        while (true)
        {
            int index = normalized.indexOf("%20");
            if (index < 0)
                break;
            normalized = normalized.substring(0, index) + " " +
            normalized.substring(index + 3);
        }

        // Resolve occurrences of "/./" in the normalized path
        while (true)
        {
            int index = normalized.indexOf("/./");
            if (index < 0)
                break;
            normalized = normalized.substring(0, index) +
            normalized.substring(index + 2);
        }

        // Resolve occurrences of "/../" in the normalized path
        while (true)
        {
            int index = normalized.indexOf("/../");
            if (index < 0)
                break;
            if (index == 0)
                return (null);  // Trying to go outside our context
            int index2 = normalized.lastIndexOf('/', index - 1);
            normalized = normalized.substring(0, index2) +
            normalized.substring(index + 3);
        }

        // Return the normalized path that we have completed
        return (normalized);
    }
	
	private static String getPid() {
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        String name = runtime.getName(); // format: "pid@hostname"
        try {
            return Integer.parseInt(name.substring(0, name.indexOf('@')))+"";
        } catch (Exception e) {
            return "";
        }
    }

}
